//
//  CategoryGridListView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 24.03.25.
//

import SwiftUI

struct CategoryGridListView: View {
    
    @Binding var categoryList:Array<AccountingCategory>
    @Binding var subCategoryList:Array<AccountingCategory>
    @Binding var selectedCategory: AccountingCategory?
    @Binding var selectedSubCategory: AccountingCategory?
    @Binding var selectedBook: AccountingBook
    @Binding var isExpand: Bool
    @State var gridItemHeight = Float(0)
    @State var placeHeight = Float(0)
    @State var rows = 0
    @State var scrollId = 0
    @State var navigatinToCategoryManager = false
    @State var isTrail = false
    @State var showTrailGuide = false
    @State var isSubCategoryChanged = false
    
    var categoryItemClick:(AccountingCategory) -> Void
    var subCategoryItemClick:(AccountingCategory) -> Void
    
    var columns = [
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top)
    ]
    
    var body: some View {
        GeometryReader { gridProxy in
            ScrollViewReader { scrollProxy in
                ScrollView {
                    LazyVGrid(columns: columns, alignment: .center) {
                        ForEach(0..<categoryList.count, id: \.self) { index in
                            let category = categoryList[index]
                            
                            VStack {
                                Button(action: {
                                    // 如果点击了同一个类别，相当于折叠操作
                                    if (sameCategory(selectedCategory: selectedCategory, category: category) && isExpand == true) {
                                        withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                                            isExpand = false
                                            selectedSubCategory = nil
                                            isSubCategoryChanged = false
                                        }
                                    } else {
                                        // 第一次点击类别，placeHeight 为零，所以需要通过监听 placeHeight 值的改变执行动画
                                        // 如果不是第一次点击，placeHeight 已经有值，监听 placeHeight 值变化的动画已经无法生效
                                        // 所以需要在点击的时候执行动画
                                        selectedSubCategory = nil
                                        isSubCategoryChanged = false
                                        subCategoryList = Array()
//                                        if (placeHeight != 0) {
//                                                selectedCategory = category
//                                                // 为了执行动画 TODO 有没有更好的办法？
//                                                if (selectedCategory?.hasSubCategory == true) {
//                                                    // 如果有子类别，会执行展开操作
//                                                    withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
//                                                        isExpand = true
//                                                        scrollProxy.scrollTo(index, anchor: UnitPoint(x: 0.5, y: 0.2))
//                                                    }
//                                                } else {
//                                                    withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
//                                                        isExpand = false
//                                                    }
//                                                    scrollProxy.scrollTo(index)
//                                                }
//                                        } else {
//                                            selectedCategory = category
//                                            if (selectedCategory?.hasSubCategory == true) {
//                                                // 如果有子类别，会执行展开操作
//                                                isExpand = true
//                                            } else {
//                                                isExpand = false
//                                                scrollProxy.scrollTo(index)
//                                            }
//                                        }
                                        if (selectedCategory?.hasSubCategory == true && isExpand) {
                                            withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                                                isExpand = false
                                            }
                                        }
                                        selectedCategory = category
                                        categoryItemClick(category)
                                    }
                                }) {
                                    CategoryGridItemView(category: category, isSelected: selectedCategory?.cid == category.cid)
                                        .overlay(GeometryReader { p in
                                            Color.clear.task {
                                                gridItemHeight = Float(p.size.height)
                                                // 如果 isSubCategoryChanged 变化了，已变化为准
                                                if !isSubCategoryChanged && isExpand && !subCategoryList.isEmpty {
                                                    let rows = ceilf(Float(subCategoryList.count) / Float(self.columns.count))
                                                    // 计算占位高度
                                                    placeHeight = rows * gridItemHeight + 10 * rows + 20
//                                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//                                                        withAnimation {
//                                                            scrollProxy.scrollTo(index, anchor: UnitPoint(x: 0.5, y: 0.2))
//                                                        }
//                                                    }
                                                }
                                            }
                                        })
                                }
                                if (category.hasSubCategory && selectedCategory?.cid == category.cid && isExpand == true) {
                                    Color.clear.frame(height: CGFloat(placeHeight))
                                }
                            }
//                            .animation(.spring(response: 0.4, dampingFraction: 0.7), value: placeHeight)
                            .overlay(alignment:.leading) {
                                Group {
                                    if (category.hasSubCategory && selectedCategory?.cid == category.cid && isExpand == true) {
                                        GeometryReader{ gridItemProxy in
                                            let overlayOffset = gridItemProxy.frame(in: .named("rootView")).minX
                                            let colWidth = gridItemProxy.size.width-20
                                            VStack (spacing: 0) {
                                                LazyVGrid(columns: columns, alignment: .center) {
                                                    ForEach(subCategoryList) { item in
                                                        Button(action:{
                                                            selectedSubCategory = item
                                                            scrollProxy.scrollTo(index, anchor: UnitPoint(x: 0.5, y: 0.2))
                                                            subCategoryItemClick(item)
                                                        }) {
                                                            CategoryGridItemView(category: item, isSelected: item.cid == selectedSubCategory?.cid)
                                                        }
                                                    }
                                                }
                                                .frame(width: gridProxy.size.width - 20)
                                                
                                            }
                                            .transition(.scale(scale: 0.01).combined(with: .opacity))
                                            .padding(.top, 20)
                                            .padding(.bottom, 10)
                                            .background(KoiArrowBackground(offset:overlayOffset+colWidth/2).fill(Color.koiColorDivider))
                                            .cornerRadius(16)
                                            .padding(.leading, 10)
                                            .padding(.trailing, 10)
                                            .offset(x:-overlayOffset, y:CGFloat(Int(gridItemHeight)+10))
                                        }
                                    }
                                }
                            }
                        }
                        Button(action: {
                            if isTrail {
                                showTrailGuide = true
                            } else {
                                navigatinToCategoryManager = true
                            }
                        }) {
                            CategoryGridItemView(category: .settingItem)
                        }
                    }
                    .padding(.bottom, isExpand ? CGFloat(placeHeight)+50 : 50)
                    .onChange(of: subCategoryList) { _ in
                        print("subCategoryList change \(subCategoryList.count)")
                        if !subCategoryList.isEmpty {
                            isSubCategoryChanged = true
                            let rows = ceilf(Float(subCategoryList.count) / Float(self.columns.count))
                            // 计算占位高度
                            placeHeight = rows * gridItemHeight + 10 * rows + 20
                            withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                                isExpand = true
                            }
                        }
                    }
                    .onChange(of: placeHeight) { value in
                        print("placeHeight change \(value)")
                    }
                    .background(Color.koiColorBackground)
                }
            }
        }
        .coordinateSpace(name:"rootView")
        .navigationDestination(isPresented: $navigatinToCategoryManager, destination: {CategoryManagerView() })
        .showTrialGuide(isShow: $showTrailGuide)
        .onAppear{
            isTrail = KoiAccountingUserManager.standard.isTrail()
        }
    }
    
    private func sameCategory(selectedCategory: AccountingCategory?, category: AccountingCategory?) -> Bool {
        return selectedCategory?.cid == category?.cid
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var categoryList = Array<AccountingCategory>()
    @Previewable @State var subCategoryList = Array<AccountingCategory>()
    @Previewable @State var selectedCategory: AccountingCategory? = AccountingCategory()
    @Previewable @State var selectedSubCategory: AccountingCategory? = AccountingCategory()
    @Previewable @State var selectedBook: AccountingBook = AccountingBook()
    @Previewable @State var isExpand: Bool = false
    CategoryGridListView(
        categoryList: $categoryList,
        subCategoryList: $subCategoryList,
        selectedCategory: $selectedCategory,
        selectedSubCategory: $selectedSubCategory,
        selectedBook: $selectedBook,
        isExpand: $isExpand,
        categoryItemClick: { _ in },
        subCategoryItemClick: { _ in}
    )
}
